
import axios from 'axios';
import type { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios';
import { getLocal } from '~/src/utils';
export default class CustomAxiosInstance {
  instance: AxiosInstance;

  axiosConfig: AxiosRequestConfig;

  /**
   *
   * @param axiosConfig - axios配置
   * @param backendConfig - 后端返回的数据配置
   */
  constructor(axiosConfig: AxiosRequestConfig){
    this.axiosConfig = axiosConfig;
    this.instance = axios.create(axiosConfig);
    this.setInstance();
  }

  setInstance(){
    this.instance.interceptors.request.use(
      async config => {
        const token = getLocal('token');
        if(token){
          config.headers['Authorization'] = `Bearer ${token}`;
        }
        console.log('config: ', config);
        return config;
      },
      (error: AxiosError) => {
        return error;

      }
    );
    this.instance.interceptors.response.use(
      async response => {
        return response;
      },
      (error: AxiosError<any>) => {
        const { response } = error;
        const msg = response?.data?.msg ?? error?.message;
        window.$message({
          type: 'error',
          message: msg || '操作失败～～'
        });
        return error;
      }
    );
  }
}
